package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2023/1/30
 *
 *      计算size = 3的基于元素个数的滚动窗口，统计每种传感器的vc的和。
 *
 *     无keyBy，不聚合
 *     
 *     Aggregate允许输入和输出不一致！
 *
 *
 */
public class Demo8_Aggregate
{
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .countWindow(3)
                   //<IN, ACC  用于存储临时累加的结果的变量类型, OUT>
                   .aggregate(new AggregateFunction<WaterSensor, Integer, String>()
                   {
                       //创建一个累加器
                       @Override
                       public Integer createAccumulator() {
                           return 0;
                       }

                       //来一条数据，累加一次
                       @Override
                       public Integer add(WaterSensor value, Integer accumulator) {
                           System.out.println("Demo8_Aggregate.add");
                           return accumulator += value.getVc();
                       }

                       //输出最终的结果
                       @Override
                       public String getResult(Integer accumulator) {
                           return "vc之和:"+accumulator;
                       }

                       //不用写。 只有批处理的API才需要实现
                       @Override
                       public Integer merge(Integer a, Integer b) {
                           return null;
                       }
                   })
                   .print();

        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
